package com.wengzw.gateway.filter;

import com.wengzw.gateway.config.JwtProperties;
import com.wengzw.gateway.utils.JWTUtil;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Component
public class JwtTokenAuthenticationFilter implements WebFilter {
    private final JwtProperties jwtProperties;
    @Resource
    private JWTUtil jwtUtil;

    public JwtTokenAuthenticationFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }


    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        String token = resolveToken(serverWebExchange.getRequest());
        if (token!=null) {
            // 验证token有效性
            Authentication authentication = jwtUtil.getAuthentication(token);
            if (authentication != null) {
                return webFilterChain.filter(serverWebExchange)
                        .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
            }
        }
        return webFilterChain.filter(serverWebExchange);
    }
    /**
     * 从请求头中获取token
     * @param request
     */
    private String resolveToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.hasLength(token))
            return token;
        return null;
    }
}
